package ${package};

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Date;
import java.util.Collections;

import javax.servlet.http.HttpServletResponse;

import com.fasterxml.jackson.core.JsonProcessingException;
import com.sdx.common.utils.JacksonUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.beetl.sql.core.engine.PageQuery;
import org.jxls.common.Context;
import org.jxls.reader.ReaderBuilder;
import org.jxls.reader.ReaderConfig;
import org.jxls.reader.XLSReadMessage;
import org.jxls.reader.XLSReadStatus;
import org.jxls.reader.XLSReader;
import org.jxls.util.JxlsHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.ModelAndView;

import com.ibeetl.admin.console.web.dto.DictExcelImportData;
import com.ibeetl.admin.console.web.query.UserQuery;
import com.ibeetl.admin.core.annotation.Function;
import com.ibeetl.admin.core.annotation.Query;
import com.ibeetl.admin.core.entity.CoreDict;
import com.ibeetl.admin.core.entity.CoreUser;
import com.ibeetl.admin.core.web.JsonResult;
import com.ibeetl.admin.core.web.JsonReturnCode;
import com.ibeetl.admin.core.util.*;
import com.sdx.common.utils.*;
import ${basePackage}.entity.*;
import ${basePackage}.service.*;
import ${basePackage}.web.query.*;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import com.ibeetl.admin.core.web.AuthorizedBaesController;


/**
 * ${entity.displayName} 接口
 */
\@RequestMapping("/${target.urlBase}/${entity.code}")
\@Controller
public class ${entity.name}Controller extends AuthorizedBaesController{
	private static final Logger log = LoggerFactory.getLogger(${entity.name}Controller.class);
    private static final String MODEL = "/${target.urlBase}/${entity.code}";

    @var service=entity.code+"Service";

    \@Resource
	private ${entity.name}Service ${service};

	/**
	 * 初始化页面需要的列表数据，
	 *
	 */
	private void setPageParam(ModelAndView view,HttpServletRequest request) {

	}

    /* 页面 */

    \@GetMapping("/index.do")
    \@Function("${basicfunctionCode}.query")
    \@ResponseBody
    public ModelAndView index(HttpServletRequest request) {
        ModelAndView view = new ModelAndView(MODEL+"/index.html") ;
		setPageParam(view,request);
        return view;
    }

    \@GetMapping("/edit.do")
    \@Function("${basicfunctionCode}.edit")
    \@ResponseBody
    public ModelAndView edit(HttpServletRequest request,${entity.idAttribute.javaType} ${entity.idAttribute.name}) {
        ModelAndView view = new ModelAndView(MODEL+"/add.html");
        ${entity.name} ${entity.code} = ${service}.queryById(${entity.idAttribute.name});
        view.addObject("${entity.code}", ${entity.code});
		setPageParam(view,request);
		try {
			view.addObject("${entity.code}Json", JacksonUtils.toJsonString(${entity.code},JacksonUtils.DF1));
		} catch (JsonProcessingException e) {
			e.printStackTrace();
		}
        return view;
    }

    \@GetMapping("/add.do")
    \@Function("${basicfunctionCode}.add")
    \@ResponseBody
    public ModelAndView add(HttpServletRequest request) {
        ModelAndView view = new ModelAndView(MODEL+"/add.html");
		setPageParam(view,request);
        return view;
    }

    /* ajax json */

    \@PostMapping("/list.json")
    \@Function("${basicfunctionCode}.query")
    \@ResponseBody
    public JsonResult<PageQuery> list(${entity.name} condtion)
    {
        PageQuery page = condtion.getPageQuery();
        ${service}.queryByCondition(page);
        return JsonResult.success(page);
    }

    private JsonResult save(boolean isNew,${entity.name} ${entity.code},HttpServletRequest request
    @for(attr in entity.list){
		@if(attr.elementType>6 && attr.elementType<11) {
							,MultipartFile ${attr.name}File
		@}
	@}
	) {
    	JsonResult result = JsonResult.success();
		String dir = DateUtil.now("yyyyMMdd");
    	String subPath = "/images/cover/"+dir+"/";
		String bucketName = "sdxcomm";
		@for(attr in entity.list){
			@if(attr.elementType>6 && attr.elementType<11) {
		if (!FileUtils.isEmptyFile(${attr.name}File)) {
			try
			{
		        String ${attr.name}FileNamePair = FileUtils.upload(subPath,${attr.name}File);
		        String ${attr.name}StoreFile = ${attr.name}FileNamePair.split("::")[0];
		        ${attr.name}StoreFile = subPath+${attr.name}StoreFile;
				AliOSSApi.uploadLocalFile(FileUtils.getRoot()+${attr.name}StoreFile,bucketName,${attr.name}StoreFile.substring(1));
				String ${attr.name}Url = "https://sdxcomm."+ConfigService.ossDomain+${attr.name}StoreFile;
				${entity.code}.set${@com.ibeetl.admin.core.gen.BaseTarget.upperFirst(attr.name)}(${attr.name}Url);
				resCloudFileService.insertResFile(ResCloudFile.ALI,${attr.name}StoreFile,${attr.name}Url,"a","老师工作照");
			}catch(Exception e) {
				e.printStackTrace();
				result.setCode(JsonReturnCode.IO_ERROR.getCode());
				result.setMsg(e.getMessage());
			}
		}
			@}
		@}
		CoreUser user = getLoginUser(request);

    	if (isNew) {
			${entity.code}.setCreatedBy(user.getId().intValue());
			${entity.code}.setCreatedName(user.getName());
			${entity.code}.setCreatedTime(new Date());
			${entity.code}.setUpdatedBy(user.getId().intValue());
			${entity.code}.setUpdatedName(user.getName());
			${entity.code}.setUpdatedTime(new Date());
			${service}.save(${entity.code});
		} else {
			${entity.code}.setUpdatedBy(user.getId().intValue());
			${entity.code}.setUpdatedName(user.getName());
			${entity.code}.setUpdatedTime(new Date());
			${service}.updateTemplate(${entity.code});
		}
		return result;
	}
    \@PostMapping("/add.json")
    \@Function("${basicfunctionCode}.add")
    \@ResponseBody
    public JsonResult add(\@Validated(ValidateConfig.ADD.class)${entity.name} ${entity.code},HttpServletRequest request
		@for(attr in entity.list){
			@if(attr.elementType>6 && attr.elementType<11) {
							,\@RequestParam("${attr.name}File") MultipartFile ${attr.name}File
			@}
		@}
		)
    {

        return save(true,${entity.code},request
		@for(attr in entity.list){
			@if(attr.elementType>6 && attr.elementType<11) {
					,${attr.name}File
			@}
		@}
		);
    }

    \@PostMapping("/update.json")
    \@Function("${basicfunctionCode}.edit")
    \@ResponseBody
    public JsonResult<String> update(\@Validated(ValidateConfig.UPDATE.class)  ${entity.name} ${entity.code},HttpServletRequest request
		@for(attr in entity.list){
			@if(attr.elementType>6 && attr.elementType<11) {
							,\@RequestParam("${attr.name}File") MultipartFile ${attr.name}File
			@}
		@}
		) {
		return save(false,${entity.code},request
		@for(attr in entity.list){
		@if(attr.elementType>6 && attr.elementType<11) {
		,${attr.name}File
@}
@}
		);
    }


   
    \@GetMapping("/view.json")
    \@Function("${basicfunctionCode}.query")
    \@ResponseBody
    public JsonResult<${entity.name}>queryInfo(${entity.idAttribute.javaType} ${entity.idAttribute.name}) {
        ${entity.name} ${entity.code} = ${service}.queryById( ${entity.idAttribute.name});
        return  JsonResult.success(${entity.code});
    }

    \@PostMapping("/delete.json")
    \@Function("${basicfunctionCode}.del")
    \@ResponseBody
    public JsonResult delete(String ids) {
		List<String> idList = Utils.strToList(ids,",");
        ${service}.batchDel${entity.name}(idList);
        return JsonResult.success();
    }
    
    @if(entity.includeExcel){
    
    \@PostMapping("/excel/export.json")
    \@Function("${basicfunctionCode}.export")
    \@ResponseBody
    public JsonResult<String> export(HttpServletResponse response,${entity.name}Query condtion) {
        /**
         * 1)需要用你自己编写一个的excel模板
         * 2)通常excel导出需要关联更多数据，因此${service}.queryByCondition方法经常不符合需求，需要重写一个为模板导出的查询
         * 3)参考ConsoleDictController来实现模板导入导出
         */
        String excelTemplate ="excelTemplates/${target.urlBase}/${entity.code}/你的excel模板文件名字.xls";
        PageQuery<${entity.name}> page = condtion.getPageQuery();
        //取出全部符合条件的
        page.setPageSize(Integer.MAX_VALUE);
        page.setPageNumber(1);
        page.setTotalRow(Integer.MAX_VALUE);
        //本次导出需要的数据
        List<${entity.name}> list =${service}.queryByCondition(page).getList();
        try(InputStream is = Thread.currentThread().getContextClassLoader().getResourceAsStream(excelTemplate)) {
            if(is==null) {
                throw new PlatformException("模板资源不存在："+excelTemplate);
            }
            FileItem item = fileService.createFileTemp("${entity.displayName}_"+DateUtil.now("yyyyMMddHHmmss")+".xls");
            OutputStream os = item.openOutpuStream();
            Context context = new Context();
            context.putVar("list", list);
            JxlsHelper.getInstance().processTemplate(is, os, context);
            os.close();
            //下载参考FileSystemContorller
            return  JsonResult.success(item.getPath());
        } catch (IOException e) {
            throw new PlatformException(e.getMessage());
        }
        
    }
    
    \@PostMapping("/excel/import.do")
    \@Function("${basicfunctionCode}.import")
    \@ResponseBody
    public JsonResult importExcel(\@RequestParam("file") MultipartFile file) throws Exception {
        if (file.isEmpty()) {
           return JsonResult.fail();
        }
        InputStream ins = file.getInputStream();
        /*解析模板并导入到数据库里,参考DictConsoleContorller，使用jxls reader读取excel数据*/
        ins.close();
        return JsonResult.success();
    }
    
    
    @}

}
